const { interpolateName } = require("loader-utils");
const schema = require("./options.json");
const path = require("path");
const { fromBuffer } = require("pdf2pic");
const createFolderIfNoExist = require("./utils-pdf2pic");
module.exports = async function (content) {
  //声明为异步loader，因为转换pdf到img的处理是异步函数
  this.async();

  const options = this.getOptions(schema);

  //   console.log(options, "options");

  //生成被转换后图片的名字
  let name = options.name || "[contenthash]-[name].pdf";
  name = interpolateName(this, name, {
    content,
  });

  //决定被转换图片的目标路径
  //webpack的输出路径是this._compiler.outputPath
  let outputPath = this._compiler.outputPath;
  if (options.outputPath) {
    outputPath = path.resolve(outputPath, options.outputPath);
  }

  //使用第三方的库 将pdf转换为图片 pdf2pic

  const pdf2imgOptions = {
    density: 100,
    saveFilename: name,
    savePath: outputPath,
    format: "png",
    width: 2550,
    height: 3000,
  };

  //check outputPath是否存在，如果不存在，则创建该文件夹
  createFolderIfNoExist(outputPath);

  const result = await fromBuffer(content, pdf2imgOptions).bulk(-1);

  console.log(result);
  const paths = result.map((img) => {
    return this.utils.contextify(this._compiler.outputPath, img.path);
  });

  console.log(paths, "paths");
  this.callback(null, `export default ${JSON.stringify(paths)}`);
};

module.exports.raw = true;
